//
//  ViewController.swift
//  IMFrame
//
//  Created by Author on 2023/9/20.
//

import UIKit
import SnapKit
protocol outputProtocol {
    func loadDataFinish()
}
let safeTop:CGFloat = UIApplication.shared.windows.first?.safeAreaInsets.top ?? 0
let safeBottom:CGFloat = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0
class ViewController: UIViewController, UITableViewDataSource {
    static let cellIdentifier = "IMMessageCell_"
    private var dataSource:[MessageModel] = []
    private lazy var presenter :Presenter = {
        let p = Presenter()
        return p
    }()
    private lazy var tableView :UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.dataSource = self
        tableView.estimatedRowHeight = 80
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.dataSource = self
        tableView.backgroundColor = .black.withAlphaComponent(12)
        return tableView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black.withAlphaComponent(12)
        addTableView()
        registCell()
        presenter.outPut = self
        presenter.loadData()
    }
    private func addTableView(){
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(safeTop)
            make.leading.trailing.bottom.equalToSuperview()
            
        }
        
    }
    private func registCell(){
        tableView.register(ChatTextCell.self, forCellReuseIdentifier: Self.cellIdentifier+"\(MessageModel.IMMessageType.text.rawValue)")
        tableView.register(ChatImageCell.self, forCellReuseIdentifier: Self.cellIdentifier+"\(MessageModel.IMMessageType.image.rawValue)")
        tableView.register(ChatVoiceCell.self, forCellReuseIdentifier: Self.cellIdentifier+"\(MessageModel.IMMessageType.voice.rawValue)")
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return presenter.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let msgModel = presenter.dataSource[indexPath.row]
        let cell:BaseTableViewCell? = tableView.dequeueReusableCell(withIdentifier: Self.cellIdentifier + "\(msgModel.messageType.rawValue)") as? BaseTableViewCell
        cell?.msg = msgModel
        cell?.eventCallback = {
            [weak self](evenType,model) in
            guard let self = self else {
                return
            }
            self.presenter.dispatchEvent(evenType, model)
        }
        return cell ?? UITableViewCell()
        
    }
}

extension ViewController: outputProtocol{
    func loadDataFinish() {
        self.tableView.reloadData()
    }
}
